<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>生成二维码</title>
		<style>
			.container {
				width: 100%;
				height: 100vh;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
			}

			.qr-code {
				margin: 20px 0 0 0;
				width: 200px;
				height: 200px;
			}
		</style>
	</head>

	<body>
		<div class="container">
			<div class="input-container">
				<input type="text" id="inp" placeholder="请输入" />
				<button>生成二维码</button>
			</div>
			<canvas id="myQrcode" class="qr-code"></canvas>
		</div>
		<script src="https://cdn.jsdelivr.net/npm/qrcode/build/qrcode.min.js"></script>
		<script type="module">
			const input = document.querySelector('#inp');
			const btn = document.querySelector('button');
			const qrCodeContainer = document.querySelector('.qr-code');

			btn.addEventListener('click', () => {
				const value = input.value;
				if (!value.trim()) return;
				drawCanvas(qrCodeContainer, value);
			});

			// 第一种，绘制到canvas
			function drawCanvas(container, value) {
				QRCode.toCanvas(container, value, function (error) {
					if (error) {
						console.error(error);
					} else {
						console.log('QR Code successfully generated!');
					}
				});
			}

			// 第二种，生成base64，放到image中
			function drawImage(container, value) {
				QRCode.toDataURL(value, function (error, url) {
					if (error) {
						console.error(error);
					} else {
						container.src = url; // 将二维码图像显示在 img 元素中
						console.log('QR Code image successfully generated!');
					}
				});
			}

			// QRCode.js 允许你定制二维码的外观，例如改变大小、颜色、容错等级等。以下是一些常用的配置项
		</script>
	</body>
</html>
